package com.inspur.cloud.service.dataspace;

import com.inspur.cloud.configuration.ApiConfig;
import com.inspur.cloud.dao.dataspace.HdfsResourceDao;
import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.entity.dataspace.ao.common.HomeAO;
import com.inspur.cloud.entity.dataspace.dto.HdfsInfo;
import com.inspur.cloud.entity.dataspace.dto.YarnInfo;
import com.inspur.cloud.enums.RoleEnum;
import com.inspur.cloud.security.AuthorizationHelper;
import com.inspur.cloud.util.TConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class HomeService {

    private static Logger log = LoggerFactory.getLogger(HomeService.class);

    public final static String[] UNIT = {"B", "K", "M", "G", "T"};

    @Autowired
    private HdfsService hdfsService;

    @Autowired
    private UserManagerService userManagerService;

    @Autowired
    private HbaseManagerService hbaseManagerService;
    @Autowired
    private HiveManagerService hiveManagerService;
    @Autowired
    private HdfsResourceDao hdfsResourceDao;
    @Autowired
    private ApiConfig apiConfig;
    @Autowired
    private YarnService yarnService;
    @Autowired
    private KafkaResourceService kafkaResourceService;
    @Autowired
    private UserResRelationSerivce userResourceRelationService;

    public HomeAO home() {
        UserEntity user = AuthorizationHelper.getUser();
        if (user.getRole() == RoleEnum.Admin.getValue()) {
            return adminHome(user);
        } else {
            return tenantHome(user);
        }
    }

    //租户首页
    private HomeAO tenantHome(UserEntity user) {
        HomeAO home = new HomeAO();
        //租户和用户信息
        Integer allUserNum = userManagerService.findByFailureTimesGreaterThanEqualAndParentId(0, user.getId()).size();
        Integer allLockUserNum = userManagerService.findByFailureTimesGreaterThanEqualAndParentId(apiConfig.getFailureTimes(), user.getId()).size();
        home.setUserNum(allUserNum - allLockUserNum);
        home.setUserLockNum(allLockUserNum);
        try {
            //hdfs信息
            if (hdfsResourceDao.findFirstByUrl(TConstants.USRPATH + TConstants.DIRECTORY + user.getName()) == null) {
                home.setHdfsUsed("0");
                home.setHdfsTotal("0");
                home.setHdfsPercent(0);
            } else {
                HdfsInfo hdfs = hdfsService.getContentSummary(TConstants.USRPATH + TConstants.DIRECTORY + user.getName());
                home.setHdfsUsed(getCapacityString(hdfs.getUsed()));
                home.setHdfsTotal(getCapacityString(hdfs.getCapacity()));
                home.setHdfsPercent(getPercent(hdfs.getUsed(), hdfs.getCapacity()));
            }
        } catch (Exception e) {
            log.error(user.getName() + "获取HDFS首页信息错误");
        }
        //hbase信息
        home.setHbaseSpaceNum(hbaseManagerService.findByLevelAndStatusAndOwner(1, 1, user.getId()).size());
        home.setHbaseTableNum(hbaseManagerService.findByLevelAndStatusAndOwner(2, 1, user.getId()).size());
        //hive信息
        home.setHiveSpaceNum(hiveManagerService.findByLevelAndStatusAndOwner(1, 1, user.getId()).size());
        home.setHiveTableNum(hiveManagerService.findByLevelAndStatusAndOwner(2, 1, user.getId()).size());
        //kafka
        home.setKafkaTopicNum(userResourceRelationService.findByUserIdAndResourceType(user.getId(), "KAFKA").size());
        try {
            //yarn
            home.setYarnInfo(deleteDefault(yarnService.getQueueInfo(user.getName(), user.getName())));
        } catch (Exception e) {
            log.error(user.getName() + "获取YARN首页信息错误");
        }
        return home;
    }

    //去掉default
    private List<YarnInfo> deleteDefault(YarnInfo root) {
        List<YarnInfo> result = new ArrayList();
        List<YarnInfo> firstList = root.getQueue();
        for (YarnInfo firstLevel : firstList) {
            if ("default".equals(firstLevel.getQueueName())) {
                continue;
            }
            YarnInfo firstYarn = new YarnInfo();
            firstYarn.setCapacity(firstLevel.getCapacity());
            firstYarn.setQueueName(firstLevel.getQueueName());
            firstYarn.setState(firstLevel.getState());
            List<YarnInfo> secondList = firstLevel.getQueue();
            if (secondList != null && secondList.size() > 0) {
                List<YarnInfo> sonResult = new ArrayList();
                for (YarnInfo secondLevel : secondList) {
                    if ((firstLevel.getQueueName() + "_default").equals(secondLevel.getQueueName())) {
                        continue;
                    }
                    YarnInfo secondYarn = new YarnInfo();
                    secondYarn.setCapacity(secondLevel.getCapacity());
                    secondYarn.setQueueName(secondLevel.getQueueName());
                    secondYarn.setState(secondLevel.getState());
                    sonResult.add(secondYarn);
                }
                if (sonResult.size() > 0) {
                    firstYarn.setQueue(sonResult);
                }
            }
            result.add(firstYarn);
        }
        return result;
    }

    //管理员首页
    private HomeAO adminHome(UserEntity user) {
        HomeAO home = new HomeAO();
        //租户和用户信息
        Integer tenantNum = userManagerService.findByFailureTimesGreaterThanEqualAndParentId(0, 1).size();
        Integer tenantLockNum = userManagerService.findByFailureTimesGreaterThanEqualAndParentId(apiConfig.getFailureTimes(), 1).size();
        Integer allUserNum = userManagerService.findAll().size();
        Integer allLockUserNum = userManagerService.findByFailureTimesGreaterThanEqual(apiConfig.getFailureTimes()).size();
        home.setTenantNum(tenantNum - tenantLockNum);
        home.setTenantLockNum(tenantLockNum);
        home.setUserNum((allUserNum - tenantNum - 1) - (allLockUserNum - tenantLockNum));
        home.setUserLockNum(allLockUserNum - tenantLockNum);
        try {
            //hdfs信息
            HdfsInfo hdfs = hdfsService.getHDFSStatus();
            home.setHdfsUsed(getCapacityString(hdfs.getUsed()));
            home.setHdfsTotal(getCapacityString(hdfs.getCapacity()));
            home.setHdfsPercent(getPercent(hdfs.getUsed(), hdfs.getCapacity()));
        } catch (Exception e) {
            log.error(user.getName() + "获取HDFS首页信息错误");
        }
        //hbase信息
        home.setHbaseSpaceNum(hbaseManagerService.findByLevelAndStatus(1, 1).size());
        home.setHbaseTableNum(hbaseManagerService.findByLevelAndStatus(2, 1).size());
        //hive信息
        home.setHiveSpaceNum(hiveManagerService.findByLevelAndStatus(1, 1).size());
        home.setHiveTableNum(hiveManagerService.findByLevelAndStatus(2, 1).size());
        //kafka
        home.setKafkaTopicNum(kafkaResourceService.findAll().size());
        try {
            //yarn信息
            home.setYarnInfo(deleteDefault(yarnService.getQueueInfo(user.getName(), "root")));
        } catch (Exception e) {
            log.error(user.getName() + "获取YARN首页信息错误");
        }
        return home;
    }

    private float getPercent(long used, long capacity) {
        DecimalFormat df = new DecimalFormat("#.00");
        return Float.valueOf(df.format(used * 100 / (double) capacity));
    }

    //获取容量字符串例如1.24K
    private String getCapacityString(Long bytes) {
        if (bytes < 1024) {
            return bytes + UNIT[0];
        }
        int times = 0;
        while (bytes > 1024 * 1024) {
            times++;
            bytes /= 1024;
        }
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(bytes / 1024.0) + UNIT[times + 1];
    }
}
